<!--
Date: 2025-08-13
Copyright (c) 2025 Industrial Software Feature Database
-->
<template>
  <el-dialog v-if="props.visible" v-model="props.visible" title="BDF文件预览" width="1200px" append-to-body
    :before-close="closeDialog">
    <el-tabs v-model="activeName" @tab-click="handleClick">
      <el-tab-pane label="模型预览" name="first">
        <div v-if="activeName == 'first'">
          <iframe ref="iframeRef" v-if="iframeVisible" :src="iframeUrl"
            style="width: 100%; height: 80vh; border: none"></iframe>
        </div>
      </el-tab-pane>
      <el-tab-pane label="文件预览" name="second">
        <div class="bdf-preview__main" v-loading="loading" v-if="activeName == 'second'">
          <el-button type="primary" @click="downloadBdf" style="margin-left: 10px">文件下载</el-button>
          <el-button v-if="showReturnBtn" @click="returnIndex" style="margin-left: 10px">返回</el-button>
          <div class="bdf" v-if="cardList.length > 0" style="display: flex;">
            <!-- 索引文件 -->
            <InfiniteList v-if="showIndexBdf" :data="cardList" :width="'100%'" :itemSize="30" :height="listHeight"
              :scrollOffset="scrollOffset" :debug="debug" v-slot="{ item, index }">
              <!-- <div class="li-con">{{ index + 1 }} : {{ item.rawDataLines[0].line }}</div> -->
              <div class="bdf-item" v-if="contentType == 'normal'">
                <p
                  :class="['pshell-item', 'bdf-con-' + item.rowNumber, currentSearchIndex == item.rowNumber ? 'active' : '']">
                  <span style="display: inline-block; width: 50px;">{{ item.rowNumber }}</span>
                  <span v-for="(place, i) in item.fields[0]" :key="i"
                    :class="[searchContent && place.indexOf(searchContent) > -1 && hasSearchContent ? 'search-item-active' : '', !place.trim() ? 'empty' : 'bg-cover']"
                    v-html="handlePlaceStr(place)"></span>
                </p>
              </div>
              <div v-else class="bdf-item">
                <p class="pshell-item" @click="linkToBdfFile(item)">
                  <span style="display: inline-block; width: 50px;">{{ item.rowNumber }}</span>
                  <span>{{ item.line }}</span>
                </p>
              </div>
            </InfiniteList>
            <!-- 其他类型文件 -->
            <div class="bdf_search-wrapper" v-if="contentType == 'normal'">
              <div class="search-btn">
                <el-input size="small" v-model="searchContent" style="width: 140px" placeholder="请输入关键词" />
                <el-button type="primary" size="small" style="margin-left: 10px" @click="searchFn">查询</el-button>
              </div>
              <div class="search-con">
                <el-select size="small" style="width: 120px;" v-model="cardType" clearable placeholder="请选择查询类型">
                  <el-option v-for="(item, index) in bdfTypeList" :key="bdfTypeList[index]" :label="bdfTypeList[index]"
                    :value="bdfTypeList[index]"></el-option>
                </el-select>
                <el-text style="margin-left: 20px;" class="mx-1">{{ pageIndex }}</el-text>/<el-text
                  style="margin-right: 10px;" class="mx-1">{{ markIndexList.length }}</el-text>
                <el-icon :disabled="pageIndex <= 1" size="small" color="#000" @click="preFn">
                  <ArrowUp />
                </el-icon>
                <el-icon :disabled="pageIndex >= markIndexList.length" size="small" color="#000" @click="nextFn">
                  <ArrowDown />
                </el-icon>
                <el-icon size="small" color="#000" @click="delFn">
                  <Close />
                </el-icon>
              </div>

              <div class="node-statistics">
                <el-collapse v-model="activeNames">
                  <el-collapse-item title="节点统计信息" name="1" :icon="CaretRight">
                    <div v-if="cardCount" class="node-statistics-item">
                      <div class="con" v-for="(val, key) in cardCount" :key="key">
                        <span> - {{ key }}:</span> <el-link type="primary" @click="linkToCard(key)">{{ val }}</el-link>
                      </div>
                    </div>
                  </el-collapse-item>
                </el-collapse>
              </div>
            </div>
          </div>
        </div>
      </el-tab-pane>
    </el-tabs>

    <template #footer>
      <div class="dialog-footer" style="text-align: center;">
        <el-button type="primary" size="small" @click="closeDialog">关闭窗口</el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup name="BdfFilePreview">
import InfiniteList from 'vue3-infinite-list';
import { previewNaturalMesh, downloadNaturalMeshFile, searchNaturalMeshItem, bdfPreview } from '@/api/dataAcquisition';
import { bdfFileFunc } from "../fileDownload.js";
const { downloadFileWithAxios } = bdfFileFunc();
const emit = defineEmits(['handleEvent']);
const props = defineProps(['bdfItem', 'visible']);
const loading = ref(false);
const cardList = ref([]);
const cardCount = ref(null);
const contentType = ref(''); // 文件类型
const debug = ref(false);
const scrollOffset = ref(0); // 指定滚动位置
// BDF预览相关信息
const searchContent = ref('');
const hasSearchContent = ref(false);
const currentSearchIndex = ref(null);
const bdfTypeList = ref([]);
const cardType = ref('');
const pageIndex = ref(1);
const markIndexList = ref([]);
const activeNames = ref(['1']);
const bdfTypeMap = ref({});
const listHeight = ref(0);
const showIndexBdf = ref(false); // 默认不展示索引下的普通文件
const showReturnBtn = ref(false);
const indexBdfUrl = ref('');
const idStack = ref([]);
const iframeUrl = ref('');
const iframeRef = ref(null)
// const listHeight = computed(() => {
//   console.log('height', document.querySelector('.bdf') && document.querySelector('.bdf').getBoundingClientRect().height)
//   return document.querySelector('.bdf') && document.querySelector('.bdf').getBoundingClientRect().height;
// });
const linkToCard = (key) => {
  // let fOne = 0;
  // cardList.value.forEach((item, index) => {
  //   if (item?.name === key)    {
  //     scrollOffset.value = index * 30; // 重置滚动位置
  //     return;
  //   }        
  // })
  for (let i = 0; i < cardList.value.length; i++) {
    if (cardList.value[i].name === key) {
      scrollOffset.value = i * 30; // 重置滚动位置
      break;
    }
  }
}
const activeName = ref('first');
const handleClick = () => { }
const downloadBdf = () => {
  let downloadItem = idStack.value.at(-1);
  downloadFileWithAxios(downloadItem?.meshModelId, loading, 2)
}
// place字符串空格处理
const handlePlaceStr = (str) => {
  let len = str.trim().length;
  let emptyHtml = '';
  if (8 - len > 0) {
    for (let i = 0; i < 8 - len; i++) {
      emptyHtml += '<span style="width:6.675px;display: inline-block;"></span>';
    }
  }
  return str + emptyHtml;
}
// pshell点击事件
const pshellClick = (item) => {
  let data = version.value.find(item => item.versionNumber === currentTab.value);
  pshellItem.value = {
    ...item,
    versionNumber: data.versionNumber,
    remarks: data.remarks,
  };
  pshellDialogShow.value = true;
}
// 索引文件跳转普通bdf文件
const linkToBdfFile = (row) => {
  if (row.meshModelId) {
    idStack.value.push({
      meshModelId: row.meshModelId,
      fileName: row.relativePath
    });
    getBdfDetail(row.meshModelId, true);
  }
}
const returnIndex = () => {
  idStack.value.pop();
  getBdfDetail(idStack.value.at(-1).meshModelId, false)
}
const searchFn = () => {
  // if (!searchContent.value || searchContent.value.length !== 8) {
  //   // findText();
  //   ElMessage({ showClose: true, message: '请输入8位字符串进行查询', type: 'waring' });
  //   return;
  // }
  let val = searchContent.value;
  searchNaturalMeshItem({
    "id": props?.bdfItem?._id,
    "cardName": cardType.value,
    "value": val.trim()
  }).then(res => {
    hasSearchContent.value = true;
    markIndexList.value = res.data.matchNumberList;
    currentSearchIndex.value = markIndexList.value[0]; // 重置搜索位置
    cardList.value.forEach((item, index) => {
      if (item?.rowNumber === currentSearchIndex.value) {
        scrollOffset.value = index * 30; // 重置滚动位置
        return;
      }
    })
    pageIndex.value = 1; // 重置页数

  }).catch(e => {
    scrollOffset.value = 0;
    currentSearchIndex.value = -1;
    hasSearchContent.value = false;
    markIndexList.value.length = 0;
    pageIndex.value = 1;
  })
};

// 下一个
const nextFn = () => {
  if (!hasSearchContent.value) return;
  if (pageIndex.value === markIndexList.value.length) {
    ElMessage({ showClose: true, message: '已是匹配的最后一条数据', type: 'waring' });
    return;
  }
  pageIndex.value++;
  currentSearchIndex.value = markIndexList.value[pageIndex.value - 1];
  cardList.value.forEach((item, index) => {
    if (item?.rowNumber === currentSearchIndex.value) {
      scrollOffset.value = index * 30; // 重置滚动位置
      return;
    }
  })
};
// 上一个
const preFn = () => {
  if (!hasSearchContent.value) return;
  if (pageIndex.value === 1) {
    ElMessage({ showClose: true, message: '已是匹配的第一条数据', type: 'waring' });
    return;
  }
  pageIndex.value--;
  currentSearchIndex.value = markIndexList.value[pageIndex.value - 1];
  cardList.value.forEach((item, index) => {
    if (item?.rowNumber === currentSearchIndex.value) {
      scrollOffset.value = index * 30; // 重置滚动位置
      return;
    }
  })
};
const delFn = () => {
  cardType.value = '';
  currentSearchIndex.value = -1;
  markIndexList.value.length = 0;
  searchContent.value = '';
  pageIndex.value = 1;
  scrollOffset.value = 0;
}
// 处理Pshell编辑事件
const handlePshellEdit = async (data) => {
  pshellDialogShow.value = false;
  if (data.type === 'refresh') {
    // 生版后重新渲染零件详情页
    await queryModelDetail();
    if (activeName.value === 'bdf') {
      currentTab.value = version.value[version.value.length - 1].versionNumber;
      let data = version.value.find(item => item.versionNumber === currentTab.value);
      updateBdfInfo(data);
      delFn();
    }
  }
};
const closeDialog = () => {
  iframeUrl.value = '';
  emit('handleEvent', { type: 'cancel' });
};
// flag true - 展示index下的普通文件  false 展示当前文件
const getBdfDetail = (id, flag = false) => {
  loading.value = true; //props?.bdfItem?._id
  showIndexBdf.value = false;
  if (id != props?.bdfItem?._id) {
    showReturnBtn.value = true;
  } else {
    showReturnBtn.value = false;
  }
  previewNaturalMesh({ _id: id }).then(res => {
    loading.value = false;
    contentType.value = res.data.contentType;
    // cardList.value = res.data?.bulkDataEntry?.cardList || [];
    // cardCount.value = res.data?.bulkDataEntry?.cardCount || null;
    // bdfTypeList.value = res.data?.bulkDataEntry?.cardCount ? Object.keys(res.data?.bulkDataEntry?.cardCount) : [];
    if (contentType.value !== 'normal') {
      cardList.value = res.data?.parsedDataLines || [];
    } else {
      cardList.value = res.data?.cardList || [];
      cardCount.value = res.data?.cardCount || null;
      bdfTypeList.value = res.data?.cardCount ? Object.keys(res.data?.cardCount) : [];
    }
    showIndexBdf.value = true;
    nextTick(() => {
      listHeight.value = document.querySelector('.bdf') && document.querySelector('.bdf').getBoundingClientRect().height;
    })
  }).catch(err => {
    loading.value = false;
    console.log(err);
  }).finally(() => {
    loading.value = false;
  });
};

onMounted(() => {
  idStack.value = [{
    meshModelId: props?.bdfItem?._id,
    fileName: props.bdfItem.fileName
  }];
  //67bd686f5ca20b6d97566b01
  //67bd686f5ca20b6d97566a9c
  props?.bdfItem?._id && getBdfDetail(props?.bdfItem?._id);

  bdfPreview(props?.bdfItem?._id.toString()).then(res => {
    if (res) {
      iframeUrl.value = res?.data?.renderUrl || '';
    }
  })

});
</script>

<style lang="scss" scoped>
.bdf-preview__main {
  .bdf {
    position: relative;
    width: 100%;
    height: calc(100vh - 250px);
    // max-height: 300px;
    display: flex;
    flex-direction: row;

    // align-items: end;
    .bdf_div {
      flex: 1;

    }

    .bdf-item {
      .pshell-item {
        cursor: pointer;

        span:nth-child(odd) {
          &.bg-cover {
            background: rgba(0, 0, 0, 0.1);
          }

          &.search-item-active {
            background: pink;
          }
        }
      }
    }

    .active {
      color: blue;
    }

    .search-item-active {
      background: pink;
    }

    .bdf_search-wrapper {
      flex: 0 0 300px;

      .search-btn {
        padding: 0 5px;
      }

      .search-con {
        display: flex;
        align-items: center;
        // margin-top: 10px;
        padding: 5px;

        .el-icon {
          font-size: 16px;
          margin-left: 5px;
        }
      }

      .node-statistics {
        // max-height: calc(100vh - 200px);
        // overflow-y: scroll;
        // padding: 5px;
        height: calc(100% - 60px);
        overflow-y: auto;

        .node-statistics-item {
          // max-height: calc(100vh - 200px);
          // overflow-y: scroll;
          // padding: 5px;
        }
      }
    }

    .bdf_search {
      // width: 500px;
      position: sticky;
      top: 0;
      display: flex;

      border: 1px solid #e8e8e8;
      padding: 5px 10px;
      // border-radius: 10px;
      background: #fff;
    }
  }
}
</style>
